import SparkMD5 from 'spark-md5';
import {reactive} from "vue"; // 引入 spark-md5 库

export const calculateFileMD5Async = async (file, onProgress) => {
    try {
        const chunkSize = 1024 * 1024 * 5
        const totalChunks = Math.ceil(file.size / chunkSize);

        const md5 = new SparkMD5.ArrayBuffer();

        for (let chunkIndex = 0; chunkIndex < totalChunks; chunkIndex++) {
            const start = chunkIndex * chunkSize;
            const end = Math.min(start + chunkSize, file.size);
            const chunk = file.slice(start, end);

            const arrayBuffer = await readFileBuffer(chunk);
            md5.append(arrayBuffer)

            const progress = (chunkIndex + 1) / totalChunks * 100;
            onProgress(progress,file.uid);
        }

        return md5.end();
    } catch (error) {
        console.error("Error calculating MD5:", error);
        throw error;
    }
};

const readFileBuffer = (file) => {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();

        reader.onload = (event) => {
            resolve(event.target.result);
        };

        reader.onerror = (error) => {
            reject(error);
        };

        reader.readAsArrayBuffer(file);
    });
};

